package com.yanhao.viewmode

import androidx.lifecycle.*
import com.yanhao.bean.Project
import com.yanhao.etx.error
import com.yanhao.repository.ProjectRepository
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class ProjectViewModel(private val resp: ProjectRepository) : BaseViewModel() {
    private var _projectTreeTitle = MutableLiveData<MutableList<Project>>()
    val projectTreeTitle: LiveData<MutableList<Project>>
        get() = _projectTreeTitle

    fun getProjectTabTitle() {
        viewModelScope.launch {
            flow {
                val result = resp.getProjectTabTitle()
                emit(result)
            }.catch {e :Throwable->
                errorCatch(e)
            }.onStart {

            }.onCompletion {

            }.collect {
                it?.let {
                    if (it.errorCode == 0) {
                        val datas = it.data
                        _projectTreeTitle.value = datas
                    }
                }
            }
        }
    }

}

class ProjectViewModelFactory : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(ProjectViewModel::class.java)) {
            return ProjectViewModel(resp = ProjectRepository()) as T
        }
        throw IllegalArgumentException("不能找到 ProjectViewModelFactory")
    }

}